<template>
  <div class="AddOrUpdate_main add_container column_one">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="兑换极分：" prop="applyPoints">
          <el-input v-model.number="formData.applyPoints" placeholder="请输入" clearable oninput="value=value.replace(/[^0-9]/g,'')" />
        </el-form-item>
      </el-form>
      <div class="tip1">可兑换总极分：{{ latestPoints }}</div>
      <div class="tip2">1极分=1元</div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">确认</el-button>
    </div>
  </div>
</template>

<script>
import { getPoints, cash } from '@/api/common/personalCenter'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },

  data() {
    const validatePoints = (rule, value, callback) => {
      if (!value) {
        callback(new Error('兑换极分不能为空'))
      } else if (Number(value) < 5) {
        callback(new Error('兑换极分不得低于5'))
      } if (Number(value) > Number(this.latestPoints)) {
        callback(new Error('兑换极分不得大于总极分'))
      } else {
        callback()
      }
    }
    return {
      latestPoints: '0',
      formData: {
        applyPoints: ''
      },
      rules: {
        applyPoints: [
          { required: true, validator: validatePoints, trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getPoints()
  },
  methods: {
    getPoints() {
      getPoints(this.$store.state.user.userId).then(res => {
        this.latestPoints = res.data.latestPoints
      })
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          cash({ ...this.formData, applyBy: this.$store.state.user.userId }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.getPoints()
            this.$parent.getById()
          })
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-form-item__label{
    width: 100px !important;
}
.tip1{
    padding-left: 20px;
    font-size: 14px;
}
.tip2{
    width: 100%;
    padding-right: 20px;
    color: #999999;
    text-align: right;
}
</style>
